const app = document.getElementById("app");

export const createSprite = async (
  style = { x, y, width, height }
) => {
  const div = document.createElement("div");
  styleSprite(div, style);
  app.appendChild(div);
  return div;
};

export const styleSprite = (sprite, { bottom, right ,left,top, width, height }) => {
  sprite.classList.add('sprite');
  sprite.style.position = 'absolute';
  sprite.style.left = left + 'px';
  sprite.style.top = top + 'px';
  sprite.style.bottom = bottom + 'px';
  sprite.style.right = right + 'px';
  sprite.style.width = width + 'px';
  sprite.style.height = height + 'px';
};

export const drawDom = (rootNode) => {
  console.log("rootNode===", rootNode);
  
  const style = rootNode.getComputedLayout()
  
  createSprite( style);
  const index = rootNode.getChildCount();
  if (index > 0) {
    for (let i = 0; i < index; i++) {
      const child = rootNode.getChild(i);
      draw(child);
    }
  }
};

export const draw = (layoutTree) => {
  // 删除所有已存在的 sprite 元素
  const existingSprites = document.querySelectorAll('.sprite');
  existingSprites.forEach(sprite => sprite.remove());

  drawDomEach(layoutTree)
};

export const drawDomEach = (layoutTree) => {

  // 创建当前节点的 sprite
  createSprite(layoutTree.layout);

  // 递归处理子节点
  if (layoutTree.children && layoutTree.children.length > 0) {
    layoutTree.children.forEach(child => {
      drawDomEach(child);
    });
  }
};